#!/usr/bin/env python

# This file takes a directory of sound files, and a directory of jpg files, 
# and for each sound file, allows you to match, using a select file dialog, 
# an image file with a sound file, in order to rename the image file with 
# the sound file's basename. The idea is that you have your sound files 
# named the way you want, and you have a folder of album covers that you 
# downloaded, with meaningful names, but not in the format you want. The 
# soundfile name is in the title bar. Best to maximize the dialog window. 
# If you don't have an image file for a particular soundfile, or if you want 
# to quit, just cancel, and you will be asked to confirm the quit. All albums 
# that were not paired up with an image file are printed to stdout. 
# 
# This moves the source image files to a subfolder called 'old', which speeds 
# things up, since the list of files to choose from shrinks as you go.

import glob
import os
from tkFileDialog import askopenfilename, askdirectory
import shutil
from tkMessageBox import askyesno

imagedir = askdirectory(title='Choose Image folder')
sounddir = askdirectory(title='Choose Soundfile folder')
soundlist = glob.glob(os.path.join(sounddir,'*.flac'))

targetdir = os.path.join(imagedir, 'new')
if not os.path.exists(targetdir):
  os.makedirs(targetdir)

backupdir = os.path.join(imagedir, 'old')
if not os.path.exists(backupdir):
  os.makedirs(backupdir)

for f in soundlist:
  basename = os.path.splitext(os.path.basename(f))[0]
  filename = askopenfilename(filetypes=(('jpg Files', '*.jpg'),("All Files", "*")), initialdir=imagedir,title=basename)
  if filename:
    imageextension = os.path.splitext(filename)[1]
    imagebasename = os.path.splitext(os.path.basename(filename))[0]
    imagefilepath = os.path.dirname(filename)
    shutil.copyfile(filename, os.path.join(imagefilepath,'old',imagebasename+imageextension))
    os.rename(filename, os.path.join(imagefilepath,'new',basename+imageextension))
  else:
    print basename
    if askyesno("renamer", "Quit?"):
      break
